import { observable, action } from 'mobx';
import { FROMWEITETABKEYS } from '../../constants/form';
import ListViewStore from '../../common/list-view/Store';
import { ListView } from 'weaver-mobile'; 
import app from '../../apis/app.js';

const dataSource =  new ListView.DataSource({
  rowHasChanged: (row1, row2) => row1 !== row2,
});
const pageSize = 20;

export default class WriteStore {
  @observable noFilledSearchVal = '';
  @observable filledSearchVal = '';
  @observable filledLvpStore = new ListViewStore();
  @observable noFilledData = dataSource.cloneWithRows([]);
  @observable allNoFilledData = [];
  @observable noFilledDataPage = 1;
  @observable noFillLoading = false;

  @action init = () => {
    this.noFilledSearchVal = '';
    this.filledSearchVal = '';

    this.filledLvpStore.clearData();

    this.getApps(FROMWEITETABKEYS.NOFILLED);
    this.getApps(FROMWEITETABKEYS.FILLED);
  
    this.allNoFilledData = [];
    this.noFilledDataPage = 1;
  }

  @action onSearchValChange = (key, val) => {
    if (key === FROMWEITETABKEYS.NOFILLED) {
      this.noFilledSearchVal = val;
    } else {
      this.filledSearchVal = val;
    }

    this.getApps(key);
  }

  @action getApps = key => {
    let searchText = '';

    if (key === FROMWEITETABKEYS.NOFILLED) {
      searchText = this.noFilledSearchVal;

      this.noFilledData = dataSource.cloneWithRows([]);
      this.noFillLoading = true;

       app.listToBeFilled({
         searchText: searchText
       }).then(res => {
          this.noFillLoading = false;
          this.allNoFilledData = res;

          this.noFilledData = this.noFilledData.cloneWithRows(res.slice(0, pageSize));
       })

    } else {
      searchText = this.filledSearchVal;

      const _getDataKey = () => app.listFilledHistory({
        searchText: searchText,
      }).then(result => {
        return result.sessionkey.datas;
      });

      return this.filledLvpStore.getData(_getDataKey);
    }
  }

  @action onEndReached = () => {
    this.noFilledDataPage = this.noFilledDataPage + 1;
    this.noFilledData = this.noFilledData.cloneWithRows(this.allNoFilledData.slice(0, this.noFilledDataPage * pageSize))
  }
}